package com.example.user.service.impl;

import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.validation.BindException;

import java.util.Objects;

/**
 * @BelongsProject: fourperiodtest
 * @BelongsPackage: com.example.user.service.impl
 * @Author: 江岸
 * @CreateTime: 2020-06-30 11:32
 * @Description: 全局异常捕捉。此处仅捕捉@valid引发的异常
 */
@ControllerAdvice
public class GlobalExceptionHandler {


    @ResponseBody
    @ExceptionHandler(BindException.class)
    public String handleValidException(BindException e){
        //将错误信息返回给前台
        return Objects.requireNonNull(e.getBindingResult().getFieldError()).getDefaultMessage();
    }
}
